<template>
  <div>
    <!-- 搜索 -->
    <el-input v-model="filterText" class="search mrg-t-10" placeholder="请输入内容" size="small">
      <template #prefix>
        <el-icon class="el-input__icon">
          <search />
        </el-icon>
      </template>
    </el-input>
    <!-- 树 -->
    <div class="tops">
      <el-tree
        ref="treeRef"
        :data="data"
        :filter-node-method="filterNode"
        :props="defaultProps"
        default-expand-all
        highlight-current
        node-key="id"
        :expand-on-click-node="false"
        @node-click="handleNodeClick"
      >
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <i v-if="node.level === 1" class="father" />
            <i v-else-if="node.level === 2" class="son" />

            <span style="font-size: 14px !important">
              {{ data.name }}
            </span>
          </span>
        </template>
      </el-tree>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, watch, watchEffect } from "vue"
interface defaultPropsTypes {
  children: string
  label: string
}
interface PropsTypes {
  data: any
  defaultProps?: defaultPropsTypes
}

const props = withDefaults(defineProps<PropsTypes>(), {
  data: [],
  defaultProps: { children: "children", label: "label" }
})

// const data = ref([])

const treeRef = ref(null)
const filterText = ref("")
const emit = defineEmits(["handleShow"])
const handleNodeClick = async (curNodeEvent, nodeAttribute, treeNodeEvent, E) => {
  if (nodeAttribute.level === 1) {
    emit("handleShow", true, curNodeEvent.id)
  } else {
    emit("handleShow", false, curNodeEvent.id)
  }
}

watch(
  () => props.data,
  () => {
    if (props.data.length) {
      nextTick(() => {
        treeRef.value?.setCurrentKey(props.data[0].id)
      })
    }
  },
  {
    deep: true
  }
)
watch(filterText, (val) => {
  treeRef.value?.filter(val)
})

const filterNode = (value, data) => {
  if (!value) return true
  return data.label.includes(value)
}
</script>

<style lang="scss" scoped>
@import "./Tree";
</style>
